package com.aistar.service.es_search.impl;

import com.aistar.mapper.TravelnoteMapper;
import com.aistar.pojo.PageEs;
import com.aistar.pojo.Travelnote;
import com.aistar.service.es_search.ES_SearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shkstart
 * @date 2019/10/14 - 21:51
 */
@Service("TravelnoteES_SearchServiceImpl")
public class TravelnoteES_SearchServiceImpl implements ES_SearchService<Travelnote> {
    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    TravelnoteRepository travelnoteRepository;
    @Override
    public PageEs<Travelnote> queryResult(PageEs pageParameter, String ansText) {
        PageEs<Travelnote> pageEs = new PageEs<>();
//        构建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        QueryBuilder builder1 = QueryBuilders.matchQuery("travText",ansText);
        if(!ansText.equals("")){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.boolQuery().must(builder1));
        }
//        分页
        nativeSearchQueryBuilder.withPageable(PageRequest.of(pageParameter.getCurrPage()-1,pageParameter.getPageSize()));
//        搜素，获取结果

        Page<Travelnote> travelnotes = this.travelnoteRepository.search(nativeSearchQueryBuilder.build());
        pageEs.setTotalSize(travelnotes.getTotalElements());
        pageEs.setCurrPage(travelnotes.getNumber()+1);
        pageEs.setDataList(travelnotes);
        return pageEs;
    }

    @Autowired
    TravelnoteMapper travelnoteMapper;
    @Override
    public List<Travelnote> queryAllResults() {
        return travelnoteMapper.selectByExampleWithBLOBs(null);
    }
}
